﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

/// <summary>
/// WebConnection 的摘要说明
/// </summary>
public class WebConnection
{
    HttpContext context;
    MyLog mylog;

    public WebConnection(HttpContext context)
    {
        this.context = context;
        mylog = new MyLog(context);
    }


    /// <summary>
    /// post JSON 到 url
    /// </summary>
    /// <param name="url"></param>
    /// <param name="json"></param>
    /// <returns></returns>
    public string PostRequestJson(string url, string json)
    {
        string result = "";

        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Timeout = int.MaxValue;
            req.Method = "POST";
            req.ContentType = "application/json; charset=utf-8";
            byte[] data = Encoding.UTF8.GetBytes(json);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();

            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
        }
        catch (Exception ee)
        {
            mylog.writeLog("【url】:" + url + "\r\n" + ee.ToString());
        }

        return result;
    }


    /// <summary>
    /// get 方法，获取返回的json
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public string GetRequestJson(string url, string codingType)
    {
        string ret2 = "";

        try
        {
            Encoding encoding;
            if (codingType == "GBK")
                encoding = Encoding.GetEncoding("GBK");
            else
                encoding = Encoding.UTF8;

            HttpWebRequest webReq2 = (System.Net.HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response2 = (HttpWebResponse)webReq2.GetResponse();
            StreamReader sr2 = new StreamReader(response2.GetResponseStream(), encoding);
            ret2 = sr2.ReadToEnd();
        }
        catch (Exception ee)
        {
            mylog.writeLog("【url】:" + url + "\r\n" + ee.ToString());
        }

        return ret2;
    }
}